<?php
namespace Reseller\Model;

/**
 * 后台首页控制器
 */
class SaleMangerModel extends BaseModel
{

    public function __construct()
    {
        parent::__construct();
        $this->orderType = session('reseller_user.shop_or_reseller');
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $m      = M('line_orders');
        $oid    = I('order_id');
        $status = $m->where(['order_id' => $oid])->getField('order_status');
        //必须是未支付的订单
        if (!($status == -1 || $status == -2)) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }
        M()->startTrans();
        //释放余位
        $res = $this->resetSeat($oid);
        if ($m->where(['order_id' => $oid])->save(['order_status' => -6]) !== false && $res) {
            M()->commit();
            return ['status' => 1, 'msg' => '操作成功'];
        }
        M()->rollback();
        return ['status' => -2, 'msg' => '操作失败'];
    }

    /**
     * 确认支付
     */
    public function confirmPay()
    {
        $m   = M('line_orders as l');
        $oid = I('order_id');
        //必须是未支付的订单
        $status = $m
            ->field('order_status,group_status')
            ->join('__PUBLIC_GROUP__ as g on l.group_id = g.group_id')
            ->where(['order_id' => $oid])
            ->find();

        if ($status['order_status'] != -1 &&
            ($status['group_status'] < 0 || $status['group_status'] > 1)) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }
        if ($m->where(['order_id' => $oid])->save(['pay_time' => time(), 'order_status' => 1]) !== false) {
            return ['status' => 1, 'msg' => '操作成功'];
        }

        return ['status' => -2, 'msg' => '操作失败'];
    }

    //释放余位
    public function resetSeat($oid)
    {
        $m_h    = M('day_hotel');
        $m_s    = M('day_seat');
        $m_t    = M('day_traffice');
        $m_g    = M('public_group');
        $detail = M('order_detail')
            ->where(['order_id' => $oid, 'source_type' => ['in', '1,2']])
            ->select();
        $order = M('line_orders')
            ->field('out_time,line_id,total_num,group_id')
            ->where(['order_id' => $oid])
            ->find();
        $out_day = date('Y-m-d', $order['out_time']);
        //把团的已收客数量减少
        $re = $m_g
            ->where(['group_id' => $order['group_id']])
            ->setDec('received_num', $order['total_num']);
        $res = $m_s
            ->where(['day' => $out_day, 'line_id' => $order['line_id']])
            ->setInc('surplus_tourist', $order['total_num']);
        if ($res === false || $re === false) {
            M()->rollback();
            die(json_encode(['status' => -1.1, 'msg' => '释放余位失败']));
        }
        // dump($detail);
        foreach ($detail as $v) {
            if ($v['source_type'] == 1) {
                $res = $m_t
                    ->where(['day' => $v['use_date'], 'traffic_priceId' => $v['source_id']])
                    ->setInc('surplus_seat', $v['adult_count'] + $v['child_count'] + $v['old_man_count']);
            } else {
                $res = $m_h
                    ->where(['day' => $v['use_date'], 'room_priceId' => $v['source_id']])
                    ->setInc('surplus_room', $v['room_count']);
            }
            // echo M()->_sql();echo '<br>';
            if ($res === false) {
                M()->rollback();
                die(json_encode(['status' => -1.2, 'msg' => '释放余位失败']));
            }
        }
        return true;
    }

    /**
     * 更改订单状态为已退款
     */
    public function refuse()
    {
        $oid    = I('order_id');
        $m      = M('line_orders');
        $status = $m->where(['order_id' => $oid])->getField('order_status');
        //审核通过的订单才能退款
        if ($status != 3) {
            return ['status' => -2, 'msg' => '订单状态错误'];
        }

        $res = $m->where(['order_id' => $oid])->save([
            'order_status' => -3,
            'back_money'   => I('back_money'),
            'end_need_pay' => I('close_money'),
            'refund_time'  => time(),
            'is_refund'    => 0,
        ]);
        if ($res !== false) {
            return ['status' => 1, 'msg' => '退款申请已提交'];
        }

        return ['status' => -1, 'msg' => '操作失败'];
    }

    /**
     * 订单列表
     * @param array   $where
     * @param string  $order_status 订单状态
     * @param string  $refund_conf   连表的条件
     */
    public function orderList($where, $order_status, $refund_conf = '')
    {
        $reseller_id = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        //数据总条数
        $count = M('line_orders as lo')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and (lo.order_status in ({$order_status}) {$refund_conf})  and order_type = {$this->orderType} and is_contact = 1")
            // ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = '{$reseller_id}' and rp_type={$this->orderType}) or rp_type = 0)")
            ->where($where)
            ->getField('count(*)');

        $page = new \Think\Page($count, 15);
        $show = $page->show();
        $list = M('line_orders as lo')
            ->field('lo.order_id,lo.order_num, l.line_name, l.group_num,
                t.tourists_name, t.tourists_phone, lo.total_num,
                lo.adult_num, lo.child_num, lo.oldMan_num,
                p.adult_price, p.child_price, p.oldman_price,
                l.origin_id, lo.create_time, lo.sales_id,
                lo.order_status, lo.manager_id,g.group_status,is_refund,origin_line_id')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and (lo.order_status in ({$order_status}) {$refund_conf})  and order_type = {$this->orderType} and is_contact = 1")
            ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join('__PUBLIC_GROUP__ as g on lo.group_id = g.group_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = '{$reseller_id}' and rp_type={$this->orderType}) or rp_type = 0)")
            ->where($where)
            ->order('lo.order_id desc')
            ->limit($page->firstRow, $page->listRows)
            ->select();
        //退款列表
        if ($refund_conf || $order_status == -3 || $order_status == -5) {
            $this->refund = 1;
        }

        $this->arrangeData($list);

        return ['list' => $list, 'show' => $show];
    }

    /**
     * 导出excel
     * @param array   $where
     * @param string  $order_status 订单状态
     */
    public function exportExcels($where, $order_status, $refund_conf = '')
    {

         $reseller_id = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        $list = M('line_orders as lo')
            ->field('lo.order_id,lo.order_num, l.line_name, l.group_num,
                t.tourists_name, t.tourists_phone, lo.total_num,
                lo.adult_num, lo.child_num, lo.oldMan_num,
                p.adult_price, p.child_price, p.oldman_price,
                l.origin_id, lo.create_time, lo.sales_id,
                lo.order_status, lo.manager_id,g.group_status,is_refund,origin_line_id')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and (lo.order_status in ({$order_status}) {$refund_conf})  and order_type = {$this->orderType} and is_contact = 1")
            ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join('__PUBLIC_GROUP__ as g on lo.group_id = g.group_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = '{$reseller_id}' and rp_type={$this->orderType}) or rp_type = 0)")
            ->where($where)
            ->order('lo.order_id desc')
            ->select();

        //退款列表
        if ($refund_conf || $order_status == -3 || $order_status == -5) {
            $this->refund = 1;
            $fileName     = '退款列表';
            //订单列表
        } else {
            $expCellName['audit'] = '审核状态';
            $fileName             = '订单列表';
        }
        $this->arrangeData2($list);

        $expCellName = [
            ['order_num', '订单号'],
            ['line_name', '线路名称'],
            ['group_num', '団号'],
            ['tourists_name', '游客姓名'],
            ['tourists_phone', '联系方式'],
            ['book_num', '预定人数'],
            ['single_sale', '销售单价'],
            ['set_out', '出发城市'],
            ['create_time', '下单时间'],
            ['sales', '销售人'],
            ['group_status', '团状态'],
            ['status', '状态'],
            ['manager', '负责人'],
        ];

        $fileName = '订单列表';
        if ($order_status == -6) {
            unset($expCellName['audit']);
            $fileName = '订单回收站';
        }

        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);

    }
    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData2(&$list)
    {
        $staff = $this->changeIndex(D('Staff')->getSomeStaff(['shop_or_reseller' => $this->orderType]));
        $city  = $this->getCity();

        foreach ($list as $k => $v) {
            $list[$k]['order_num'] .= ' ';
            $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            $list[$k]['set_out']     = $city[$v['origin_id']];
            $list[$k]['sales']       = $staff[$v['sales_id']]['reseller_name'];
            $list[$k]['manager']     = $staff[$v['manager_id']]['reseller_name'];
            $list[$k]['line_name']   .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            $list[$k]['book_num']    = "预约人数：{$list[$k]['total_num']} , 大：{$list[$k]['adult_num']} , 小：{$list[$k]['child_num']} ";
            $list[$k]['single_sale'] = " 大：{$list[$k]['adult_price']} \n 小：{$list[$k]['child_price']}";
            if ($this->refund) {
                switch ($v['order_status']) {
                    case 3:
                        $list[$k]['status'] = '拒绝退款';
                        break;

                    case -3:
                        $list[$k]['status'] = '退款审核中';
                        break;

                    case -4:
                        $list[$k]['status'] = '拒绝退款';
                        break;

                    case -5:
                        $list[$k]['status'] = '已退款';
                        break;
                }
            } else {
                //订单状态处理
                switch ($v['order_status']) {
                    case -1:
                        $list[$k]['status'] = '待确认(未支付)';
                        $list[$k]['audit']  = '未审核';
                        break;

                    case 1:
                        $list[$k]['status'] = '已支付';
                        $list[$k]['audit']  = '待审核';
                        break;

                    case 3:
                        $list[$k]['status'] = '已支付';
                        $list[$k]['audit']  = '已审核';
                        break;

                    //订单回收站
                    case -6:
                        $list[$k]['status'] = '已取消';
                        $list[$k]['audit']  = '';
                        break;

                    case -4:
                        $list[$k]['status'] = '拒绝退款';
                        $list[$k]['audit']  = '已审核';
                        break;

                    case -5:
                        $list[$k]['status'] = '已退款';
                        $list[$k]['audit']  = '已审核';
                        break;
                }
            }

            switch ($v['group_status']) {
                case -1:
                    $list[$k]['group_status'] = '不成团';
                    break;
                case 0:
                    $list[$k]['group_status'] = '待出团';
                    break;
                case 1:
                    $list[$k]['group_status'] = '已成团';
                    break;
                case 2:
                    $list[$k]['group_status'] = '已出团';
                    break;
                case 3:
                    $list[$k]['group_status'] = '已回团';
                    break;
            }

        }
    }

    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData(&$list)
    {
        $staff = $this->changeIndex(D('Staff')->getSomeStaff(['shop_or_reseller' => $this->orderType]));
        $city  = $this->getCity();
        //查询订单拒绝退款记录
        $this->flag = $this->checkAuth('Reseller/SaleManger/confirmPay');
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list[$k]['set_out']     = $city[$v['origin_id']];
            $list[$k]['sales']       = $staff[$v['sales_id']]['reseller_name'];
            $list[$k]['manager']     = $staff[$v['manager_id']]['reseller_name'];
            $list[$k]['line_name']   .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            //订单状态处理
            if ($this->refund) {
                $list[$k]['html'] = $this->orderStatusRefund($v['order_status'], $v['order_id']);
            } else {
                $list[$k]['html'] = $this->orderStatus($v['order_status'], $v['order_id']);
            }

            switch ($v['group_status']) {
                case -1:
                    $list[$k]['group_text'] = '不成团';
                    break;
                case 0:
                    $list[$k]['group_text'] = '待出团';
                    break;
                case 1:
                    $list[$k]['group_text'] = '已成团';
                    break;
                case 2:
                    $list[$k]['group_text'] = '已出团';
                    break;
                case 3:
                    $list[$k]['group_text'] = '已回团';
                    break;
            }
        }
    }

    private function orderStatusRefund($order_status, $order_id)
    {
        switch ($order_status) {
            case 3:
                $html = '<td>拒绝退款</td>';
                break;

            case -3:
                $html = '<td>退款审核中</td>';
                break;

            case -4:
                $html = '<td>拒绝退款</td>';
                break;

            case -5:
                $html = '<td>已退款</td>';
                break;
        }
        return $html;
    }

    /**
     * 订单状态处理
     * @param int $order_status 订单状态
     * @param int $order_id 订单id
     * @return string  $html 页面展示内容
     */
    private function orderStatus($order_status, $order_id)
    {
        switch ($order_status) {
            case -1:
                if ($this->flag) {
                    $html = "<td><button class='btn-primary btn' onclick='confirmPay({$order_id})'>待确认<br/>(未支付)</button></td><td>未审核</td>";
                } else {
                    $html = "<td>未支付</td><td>未审核</td>";
                }

                break;

            case 1:
                $html = "<td>已支付</td><td>待审核</td>";
                break;

            case 3:
                $html = '<td>已支付</td><td>已审核</td>';
                break;

            case -6:
                $html = '已取消';
                break;

            case -4:
                $html = '<td>拒绝退款</td><td>已审核</td>';
                break;

            case -5:
                $html = '<td>已退款</td><td>已审核</td>';
                break;
        }
        return $html;
    }

    /**
     * 返回城市信息
     * @return [array] $city [可用的城市信息]
     */
    private function getCity()
    {

        $key = md5('getCity');
        if (!S($key)) {
            $city = M('areas')
                ->field('areaId,areaName')
                ->where([
                    'isShow'   => 1,
                    'areaFlag' => 1,
                    'areaType' => 1,
                ])
                ->select();
            $area_id   = array_map('array_shift', $city);
            $area_name = $this->array_cloumn($city, 'areaName');
            $city      = array_combine($area_id, $area_name);

            S($key, $city, 864000);
        }
        return S($key);
    }
}
